package com.ledi.guns.modular.ledipay.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.dao.ApplyCooperateMapper;
import com.ledi.guns.common.persistence.dao.ApplyRecordMapper;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.model.ApplyCooperate;
import com.ledi.guns.common.persistence.model.ApplyRecord;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.common.persistence.model.vo.ApplyCooperateVo;
import com.ledi.guns.common.persistence.model.vo.TaskRecordVo;
import com.ledi.guns.core.shiro.ShiroKit;
import com.ledi.guns.core.shiro.ShiroUser;
import com.ledi.guns.core.util.SystemConstans;
import com.ledi.guns.modular.ledipay.controller.req.apply.ApplyCooperateReq;
import com.ledi.guns.modular.ledipay.controller.req.apply.QueryApplyCooperate;
import com.ledi.guns.modular.ledipay.controller.req.apply.TrackApply;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.HandleWorkOrder;
import com.ledi.guns.modular.ledipay.service.ApplyCooperateService;

/**
 * 文件名称： com.ledi.guns.modular.ledipay.service.impl.ApplyCooperateServiceImpl.java<br/>
 * 初始作者： 钟小平<br/>
 * 创建日期： 2018年10月8日<br/>
 * 功能说明： 申请合作Service实现 <br/>
 * =================================================<br/>
 * 修改记录：<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (乐迪教育科技有限公司-幼儿事业部) 2017-2018.All rights reserved.<br/>
 */
@Service
public class ApplyCooperateServiceImpl implements ApplyCooperateService {

	@Resource
	private ApplyCooperateMapper applyCooperateMapper;

	@Resource
	private UserMapper userMapper;

	@Resource
	private ApplyRecordMapper applyRecordMapper;

	/**
	 * 方法描述: [新增申请合作.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年10月8日-下午1:35:30<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional
	public void addApplyCooperate(ApplyCooperateReq applyCooperateReq) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("apply_name", applyCooperateReq.getApplyName());
		List<ApplyCooperate> selectByMap = applyCooperateMapper.selectByMap(map);
		if (selectByMap.size() != 0) {
			throw new AppCheckException("apply.selectWorkOrderInfoError.code",
					"apply.selectWorkOrderInfoError.message");
		}
		ApplyCooperate entity = new ApplyCooperate();
		BeanUtils.copyProperties(applyCooperateReq, entity);
		entity.setCreateTime(new Date());
		entity.setVersionNo(SystemConstans.NO);
		entity.setStatus(SystemConstans.NO);
		entity.setIsDelete(SystemConstans.NO);
		Integer workOrderInsert = applyCooperateMapper.insert(entity);
		if (workOrderInsert < 1) {
			throw new AppCheckException("apply.addWorkOrderInfoError.code",
					"apply.addWorkOrderInfoError.message");
		}
	}

	@Override
	public Page<ApplyCooperateVo> list(Page<ApplyCooperateVo> page, QueryApplyCooperate queryApplyCooperate) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user = userMapper.selectById(currentUser.getId());
		if (1 != user.getStatus()) {
			throw new AppCheckException("apply.delete.code",
					"apply.delete.message", new Object[] { "无法操作申请" });
		}

		List<ApplyCooperateVo> searchResult = applyCooperateMapper.list(page, queryApplyCooperate.getSearch());
		page.setRecords(searchResult);
		return page;

	}

	/**
	 * 方法描述: [处理申请.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年10月8日-下午2:50:12<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional
	public void handleApply(HandleWorkOrder handleWorkOrder) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user = userMapper.selectById(currentUser.getId());
		if (1 != user.getStatus()) {
			throw new AppCheckException("apply.delete.code",
					"apply.delete.message", new Object[] { "无法处理申请" });
		}
		ApplyCooperate applyCooperate = applyCooperateMapper.selectById(handleWorkOrder.getId());
		if (null == applyCooperate) {
			throw new AppCheckException("apply.getWorkOrderInfoError.code",
					"apply.getWorkOrderInfoError.message");
		}
		Integer status = applyCooperate.getStatus();
		if (handleWorkOrder.getType() == 3) {
			if (!status.equals(SystemConstans.THREE)) {
				throw new AppCheckException("apply.checkIsCloseError.code",
						"apply.checkIsCloseError.message");
			}
			applyCooperate.setStatus(SystemConstans.TWO);
		} else {
			if (status.equals(new Byte("3"))) {
				throw new AppCheckException("apply.handleWorkOrderError.code",
						"apply.handleWorkOrderError.message");
			}
			if (handleWorkOrder.getType() == 1) {
				applyCooperate.setStatus(SystemConstans.TWO);
			} else {
				applyCooperate.setStatus(SystemConstans.THREE);
			}
		}
		applyCooperate.setVersionNo(handleWorkOrder.getVersionNo());
		applyCooperate.setUpdateTime(new Date());
		Integer handleUpdate = applyCooperateMapper.updateById(applyCooperate);
		if (handleUpdate < 1) {
			throw new AppCheckException("apply.HandleWorkOrderInfoError.code",
					"apply.HandleWorkOrderInfoError.message");
		}

		// 添加跟踪处理记录
		String contexts = "";
		if (handleWorkOrder.getType() == 3) {
			contexts = SystemConstans.ACTIVATION_WORKORDER;
		} else {
			if (handleWorkOrder.getType() == 2) {
				contexts = SystemConstans.CLOSE_WORKORDER;
			}
		}
		List<String> roleNames = currentUser.getRoleNames();
		String roles = roleNames.stream().collect(Collectors.joining(","));
		Long userId = currentUser.getId().longValue();
		ApplyRecord applyRecord = new ApplyRecord();
		applyRecord.setCreatorRole(roles);
		applyRecord.setCreateTime(new Date());
		applyRecord.setCreatorId(userId);
		applyRecord.setContent(contexts);
		applyRecord.setApplyId(handleWorkOrder.getId());
		Integer taskRecordInsert = applyRecordMapper.insert(applyRecord);
		if (taskRecordInsert < 1) {
			throw new AppCheckException("apply.insertTaskRecordError.code",
					"apply.insertTaskRecordError.message");
		}

	}

	/**
	 * 方法描述: [增加处理记录.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年10月8日-下午2:50:43<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional
	public void trackApply(TrackApply trackApply) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user = userMapper.selectById(currentUser.getId());
		if (1 != user.getStatus()) {
			throw new AppCheckException("apply.delete.code",
					"apply.delete.message", new Object[] { "无法处理申请" });
		}
		ApplyCooperate applyCooperate = applyCooperateMapper.selectById(trackApply.getApplyId());
		if (null == applyCooperate) {
			throw new AppCheckException("apply.getWorkOrderInfoError.code",
					"apply.getWorkOrderInfoError.message");
		}
		Integer status = applyCooperate.getStatus();
		if (status.equals(new Byte("3"))) {
			throw new AppCheckException("apply.handleWorkOrderError.code",
					"apply.handleWorkOrderError.message");
		}
		List<String> roleNames = currentUser.getRoleNames();
		String roles = roleNames.stream().collect(Collectors.joining(","));
		Long userId = currentUser.getId().longValue();
		ApplyRecord applyRecord = new ApplyRecord();
		applyRecord.setCreatorRole(roles);
		applyRecord.setCreateTime(new Date());
		applyRecord.setCreatorId(userId);
		applyRecord.setContent(trackApply.getContent());
		applyRecord.setApplyId(trackApply.getApplyId());
		Integer taskRecordInsert = applyRecordMapper.insert(applyRecord);
		if (taskRecordInsert < 1) {
			throw new AppCheckException("apply.insertTaskRecordError.code",
					"apply.insertTaskRecordError.message");
		}
		// change status
		applyCooperate.setStatus(SystemConstans.TWO);
		applyCooperate.setVersionNo(trackApply.getVersionNo());
		applyCooperate.setUpdateTime(new Date());
		Integer handleUpdate = applyCooperateMapper.updateById(applyCooperate);
		if (handleUpdate < 1) {
			throw new AppCheckException("apply.HandleWorkOrderInfoError.code",
					"apply.HandleWorkOrderInfoError.message");
		}

	}

	/**
	 * 方法描述: [ 获取跟踪内容.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年10月8日-下午2:56:50<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public List<TaskRecordVo> getApplyRecord(Long id) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user1 = userMapper.selectById(currentUser.getId());
		if (1 != user1.getStatus()) {
			throw new AppCheckException("apply.delete.code",
					"apply.delete.message", new Object[] { "无法处理申请" });
		}
		List<TaskRecordVo> result = new ArrayList<>();
		List<ApplyRecord> taskRecordLists = applyRecordMapper.selectList(new EntityWrapper<ApplyRecord>()
				.eq("apply_id", id)
				.orderBy("createTime", false));

		taskRecordLists.forEach(taskRecordList -> {
			TaskRecordVo taskRecordVo = new TaskRecordVo();
			taskRecordVo.setContent(taskRecordList.getContent());
			taskRecordVo.setCreateTime(taskRecordList.getCreateTime());
			User user = userMapper.selectById(taskRecordList.getCreatorId());
			taskRecordVo.setCreator(user.getName());
			result.add(taskRecordVo);

		});
		return result;
	}
}
